import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
// 图表相关已移除
import "../components"

/**
 * 仪表详情页
 * 显示单表完整信息和实时曲线
 */
Item {
    id: root

    // 公开属性
    property int meterId: 1
    property var meterData: ({
        "meterId": 0,
        "name": "加载中...",
        "location": "---",
        "online": false,
        "ua": 0,
        "ub": 0,
        "uc": 0,
        "ia": 0,
        "ib": 0,
        "ic": 0,
        "averageVoltage": 0,
        "averageCurrent": 0,
        "totalPower": 0,
        "lastUpdateTime": new Date()
    })
    property var historyStats: ({}) // 历史统计数据

    // 刷新定时器（每秒更新一次数据和图表）
    Timer {
        id: refreshTimer
        interval: 1000
        running: false  // 初始不运行，等待 Component.onCompleted 后启动
        repeat: true
        onTriggered: {
            updateMeterData()
        }
    }
    
    // 历史统计定时器（每5分钟更新一次）
    Timer {
        id: statsTimer
        interval: 300000 // 5分钟
        running: false  // 初始不运行，等待 Component.onCompleted 后启动
        repeat: true
        triggeredOnStart: true
        onTriggered: {
            updateHistoryStats()
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 15

        // 顶部导航栏
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 60
            Layout.minimumHeight: 60
            Layout.maximumHeight: 60
            color: "white"
            radius: 8

            RowLayout {
                anchors.fill: parent
                anchors.margins: 15
                spacing: 15

                // 返回按钮
                Button {
                    text: "← 返回列表"
                    font.pixelSize: 13
                    onClicked: {
                        console.log("MeterDetailPage: 点击返回按钮")
                        try {
                            // 调用主窗口的全局函数
                            mainWindow.goBack()
                        } catch (e) {
                            console.error("MeterDetailPage: 返回出错:", e)
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 30
                    color: "#bdc3c7"
                }

                // 电表标题
                Column {
                    spacing: 4

                    Row {
                        spacing: 10

                        Text {
                            text: meterData ? meterData.name : "电表"
                            font.pixelSize: 18
                            font.bold: true
                            color: "#2c3e50"
                            anchors.verticalCenter: parent.verticalCenter
                        }

                        Rectangle {
                            width: 50
                            height: 24
                            radius: 4
                            color: "#3498db"
                            anchors.verticalCenter: parent.verticalCenter

                            Text {
                                anchors.centerIn: parent
                                text: "#" + root.meterId
                                font.pixelSize: 12
                                font.bold: true
                                color: "white"
                            }
                        }

                        Rectangle {
                            width: 60
                            height: 24
                            radius: 4
                            color: meterData && meterData.online ? "#27ae60" : "#e74c3c"
                            anchors.verticalCenter: parent.verticalCenter

                            Row {
                                anchors.centerIn: parent
                                spacing: 4

                                Rectangle {
                                    width: 8
                                    height: 8
                                    radius: 4
                                    color: "white"
                                    anchors.verticalCenter: parent.verticalCenter

                                    SequentialAnimation on opacity {
                                        running: meterData && meterData.online
                                        loops: Animation.Infinite
                                        NumberAnimation { to: 0.3; duration: 1000 }
                                        NumberAnimation { to: 1.0; duration: 1000 }
                                    }
                                }

                                Text {
                                    text: meterData && meterData.online ? "在线" : "离线"
                                    font.pixelSize: 11
                                    font.bold: true
                                    color: "white"
                                    anchors.verticalCenter: parent.verticalCenter
                                }
                            }
                        }
                    }

                    Text {
                        text: "📍 " + (meterData ? meterData.location : "位置未知")
                        font.pixelSize: 12
                        color: "#7f8c8d"
                    }
                }

                Item {
                    Layout.fillWidth: true
                }

                // 最后更新时间
                Column {
                    spacing: 4

                    Text {
                        text: "最后更新"
                        font.pixelSize: 11
                        color: "#7f8c8d"
                    }

                    Text {
                        text: {
                            if (meterData && meterData.lastUpdateTime) {
                                return Qt.formatDateTime(meterData.lastUpdateTime, "hh:mm:ss")
                            }
                            return "--:--:--"
                        }
                        font.pixelSize: 13
                        font.bold: true
                        color: "#2c3e50"
                    }
                }
            }
        }

        // 主内容区域
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.minimumHeight: 300
            clip: true
            contentWidth: availableWidth

            ColumnLayout {
                width: parent.width
                spacing: 15

                // 实时数据卡片
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 200
                    color: "white"
                    radius: 8

                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 20
                        spacing: 15

                        Text {
                            text: "📊 实时数据"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#2c3e50"
                        }

                        GridLayout {
                            Layout.fillWidth: true
                            columns: 6
                            rowSpacing: 15
                            columnSpacing: 20

                            // A相电压
                            DataItem {
                                label: "A相电压"
                                value: (meterData && meterData.ua !== undefined) ? meterData.ua.toFixed(1) : "0.0"
                                unit: "V"
                                icon: "⚡"
                                valueColor: (meterData && meterData.ua !== undefined) ? getVoltageColor(meterData.ua) : "#2c3e50"
                            }

                            // B相电压
                            DataItem {
                                label: "B相电压"
                                value: (meterData && meterData.ub !== undefined) ? meterData.ub.toFixed(1) : "0.0"
                                unit: "V"
                                icon: "⚡"
                                valueColor: (meterData && meterData.ub !== undefined) ? getVoltageColor(meterData.ub) : "#2c3e50"
                            }

                            // C相电压
                            DataItem {
                                label: "C相电压"
                                value: (meterData && meterData.uc !== undefined) ? meterData.uc.toFixed(1) : "0.0"
                                unit: "V"
                                icon: "⚡"
                                valueColor: (meterData && meterData.uc !== undefined) ? getVoltageColor(meterData.uc) : "#2c3e50"
                            }

                            // A相电流
                            DataItem {
                                label: "A相电流"
                                value: (meterData && meterData.ia !== undefined) ? meterData.ia.toFixed(2) : "0.00"
                                unit: "A"
                                icon: "⚙"
                                valueColor: (meterData && meterData.ia !== undefined) ? getCurrentColor(meterData.ia) : "#2c3e50"
                            }

                            // B相电流
                            DataItem {
                                label: "B相电流"
                                value: (meterData && meterData.ib !== undefined) ? meterData.ib.toFixed(2) : "0.00"
                                unit: "A"
                                icon: "⚙"
                                valueColor: (meterData && meterData.ib !== undefined) ? getCurrentColor(meterData.ib) : "#2c3e50"
                            }

                            // C相电流
                            DataItem {
                                label: "C相电流"
                                value: (meterData && meterData.ic !== undefined) ? meterData.ic.toFixed(2) : "0.00"
                                unit: "A"
                                icon: "⚙"
                                valueColor: (meterData && meterData.ic !== undefined) ? getCurrentColor(meterData.ic) : "#2c3e50"
                            }
                        }

                        Rectangle {
                            Layout.fillWidth: true
                            height: 1
                            color: "#ecf0f1"
                        }

                        GridLayout {
                            Layout.fillWidth: true
                            columns: 3
                            rowSpacing: 15
                            columnSpacing: 20

                            // 平均电压
                            DataItem {
                                label: "平均电压"
                                value: (meterData && meterData.averageVoltage !== undefined) ? meterData.averageVoltage.toFixed(1) : "0.0"
                                unit: "V"
                                icon: "📈"
                                highlighted: true
                                valueColor: "#3498db"
                            }

                            // 平均电流
                            DataItem {
                                label: "平均电流"
                                value: (meterData && meterData.averageCurrent !== undefined) ? meterData.averageCurrent.toFixed(2) : "0.00"
                                unit: "A"
                                icon: "📈"
                                highlighted: true
                                valueColor: "#9b59b6"
                            }

                            // 总功率
                            DataItem {
                                label: "总功率"
                                value: (meterData && meterData.totalPower !== undefined) ? (meterData.totalPower / 1000).toFixed(2) : "0.00"
                                unit: "kW"
                                icon: "🔋"
                                highlighted: true
                                valueColor: "#e74c3c"
                            }
                        }
                    }
                }

                // 历史统计
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 150
                    color: "white"
                    radius: 8

                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 20
                        spacing: 15

                        Text {
                            text: "📅 历史统计（最近24小时）"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#2c3e50"
                        }

                        GridLayout {
                            Layout.fillWidth: true
                            columns: 4
                            rowSpacing: 15
                            columnSpacing: 20

                            DataItem {
                                label: "最大电压"
                                value: historyStats.maxVoltage ? historyStats.maxVoltage.toFixed(1) : "--"
                                unit: "V"
                                icon: "⬆"
                                valueColor: "#27ae60"
                            }

                            DataItem {
                                label: "最小电压"
                                value: historyStats.minVoltage ? historyStats.minVoltage.toFixed(1) : "--"
                                unit: "V"
                                icon: "⬇"
                                valueColor: "#f39c12"
                            }

                            DataItem {
                                label: "最大电流"
                                value: historyStats.maxCurrent ? historyStats.maxCurrent.toFixed(1) : "--"
                                unit: "A"
                                icon: "⬆"
                                valueColor: "#27ae60"
                            }

                            DataItem {
                                label: "平均功率"
                                value: (historyStats.avgPower !== undefined && historyStats.avgPower !== null) ? (historyStats.avgPower / 1000).toFixed(2) : "--"
                                unit: "kW"
                                icon: "📊"
                                valueColor: "#3498db"
                            }
                        }
                    }
                }

                // 操作按钮
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: "white"
                    radius: 8

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 20
                        spacing: 15

                        Button {
                            text: "查看历史数据"
                            font.pixelSize: 13
                            Layout.preferredWidth: 150
                            onClicked: {
                                console.log("MeterDetailPage: 跳转到历史数据页面，电表ID:", root.meterId)
                                try {
                                    // 跳转到历史数据页面，并传递电表ID
                                    mainWindow.navigateTo("HistoryPage", {"selectedMeterId": root.meterId})
                                } catch (e) {
                                    console.error("MeterDetailPage: 跳转历史数据页面出错:", e)
                                }
                            }
                        }

                        Button {
                            text: "查看报警"
                            font.pixelSize: 13
                            Layout.preferredWidth: 120
                            onClicked: {
                                console.log("MeterDetailPage: 跳转到报警页面，电表ID:", root.meterId)
                                try {
                                    // 跳转到报警记录页面，并传递电表ID作为过滤条件
                                    mainWindow.navigateTo("AlarmRecordPage", {"selectedMeterId": root.meterId})
                                } catch (e) {
                                    console.error("MeterDetailPage: 跳转报警页面出错:", e)
                                }
                            }
                        }

                        Item {
                            Layout.fillWidth: true
                        }

                        Button {
                            text: "刷新数据"
                            font.pixelSize: 13
                            Layout.preferredWidth: 120
                            onClicked: {
                                console.log("MeterDetailPage: 刷新数据")
                                updateMeterData()
                                updateHistoryStats()
                            }
                        }
                    }
                }
            }
        }
    }

    // 数据项组件
    component DataItem: ColumnLayout {
        property string label: ""
        property string value: "0"
        property string unit: ""
        property string icon: ""
        property color valueColor: "#2c3e50"
        property bool highlighted: false

        spacing: 4

        Text {
            text: icon + " " + label
            font.pixelSize: 11
            color: "#7f8c8d"
        }

        Row {
            spacing: 4

            Text {
                text: value
                font.pixelSize: highlighted ? 20 : 16
                font.bold: highlighted
                color: valueColor
            }

            Text {
                text: unit
                font.pixelSize: 11
                color: "#95a5a6"
                anchors.verticalCenter: parent.verticalCenter
            }
        }
    }

    // 更新电表数据
    function updateMeterData() {
        if (!meterModel) {
            console.warn("MeterDetailPage: meterModel 未初始化")
            return
        }

        try {
            // 根据meterId从模型中获取数据
            var index = meterModel.findMeterIndex(root.meterId)
            if (index >= 0) {
                // 使用新的 getMeterData() 方法获取数据（QML 友好）
                var newData = meterModel.getMeterData(index)
                
                if (newData && Object.keys(newData).length > 0) {
                    // 调试日志：打印获取到的数据
                    console.log("MeterDetailPage: 更新数据 - Ua=", newData.ua, 
                               "Ub=", newData.ub, 
                               "Uc=", newData.uc,
                               "Ia=", newData.ia,
                               "Ib=", newData.ib,
                               "Ic=", newData.ic)
                    console.log("MeterDetailPage: 计算值 - 平均电压=", newData.averageVoltage,
                               "平均电流=", newData.averageCurrent,
                               "总功率=", newData.totalPower)
                    
                    meterData = newData
                } else {
                    console.warn("MeterDetailPage: 无法获取模型数据, index=", index)
                }
            } else {
                console.warn("MeterDetailPage: 未找到电表, meterId=", root.meterId)
            }
        } catch (e) {
            console.error("MeterDetailPage: 更新电表数据出错:", e)
            console.error("MeterDetailPage: 错误堆栈:", e.stack)
        }
    }

    // 图表功能已移除

    // 根据电压值返回颜色
    function getVoltageColor(voltage) {
        if (voltage < 200 || voltage > 250) {
            return "#e74c3c" // 红色：异常
        } else if (voltage < 210 || voltage > 240) {
            return "#f39c12" // 橙色：警告
        } else {
            return "#27ae60" // 绿色：正常
        }
    }

    // 根据电流值返回颜色
    function getCurrentColor(current) {
        if (current > 100) {
            return "#e74c3c" // 红色：过流
        } else if (current > 80) {
            return "#f39c12" // 橙色：警告
        } else {
            return "#27ae60" // 绿色：正常
        }
    }

    // 更新历史统计数据
    function updateHistoryStats() {
        // 检查historyDataBridge是否可用
        if (typeof historyDataBridge === 'undefined' || !historyDataBridge) {
            console.warn("MeterDetailPage: 历史数据桥接不可用，无法查询统计数据")
            return
        }
        
        // 查询最近24小时的统计数据
        var endTime = new Date()
        var startTime = new Date(endTime.getTime() - 24 * 60 * 60 * 1000)
        
        var startTimeStr = Qt.formatDateTime(startTime, "yyyy-MM-dd HH:mm:ss")
        var endTimeStr = Qt.formatDateTime(endTime, "yyyy-MM-dd HH:mm:ss")
        
        console.log("MeterDetailPage: 查询电表", root.meterId, "历史统计:", startTimeStr, "到", endTimeStr)
        
        try {
            var stats = historyDataBridge.queryHistoryStatistics(root.meterId, startTimeStr, endTimeStr)
            
            if (stats && Object.keys(stats).length > 0) {
                root.historyStats = stats
                console.log("MeterDetailPage: 历史统计数据更新成功: 最大电压=", stats.maxVoltage, 
                           "最小电压=", stats.minVoltage, 
                           "最大电流=", stats.maxCurrent)
            } else {
                console.warn("MeterDetailPage: 未查询到历史统计数据")
                root.historyStats = {}
            }
        } catch (e) {
            console.error("MeterDetailPage: 查询历史统计出错:", e)
        }
    }

    Component.onCompleted: {
        console.log("==== MeterDetailPage 开始加载 ====")
        console.log("MeterDetailPage: meterId=", root.meterId)
        console.log("MeterDetailPage: meterModel=", typeof meterModel !== 'undefined' ? meterModel : "undefined")
        console.log("MeterDetailPage: deviceManager=", typeof deviceManager !== 'undefined' ? deviceManager : "undefined")
        console.log("MeterDetailPage: historyDataBridge=", typeof historyDataBridge !== 'undefined' ? historyDataBridge : "undefined")
        
        try {
            console.log("MeterDetailPage: 开始更新数据...")
            // 先更新一次数据
            updateMeterData()
            console.log("MeterDetailPage: updateMeterData 完成")
            
            updateHistoryStats()
            console.log("MeterDetailPage: updateHistoryStats 完成")
            
            // 启动定时器
            console.log("MeterDetailPage: 启动定时器...")
            refreshTimer.start()
            statsTimer.start()
            
            console.log("MeterDetailPage: 加载完成！")
        } catch (e) {
            console.error("MeterDetailPage: Component.onCompleted 出错:", e)
            console.error("MeterDetailPage: 错误堆栈:", e.stack)
        }
    }
    
    Component.onDestruction: {
        console.log("MeterDetailPage: 页面销毁, meterId=", root.meterId)
        // 停止定时器
        refreshTimer.stop()
        statsTimer.stop()
    }
}

